package com.curricula.ejemplo;

import java.io.File;

import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.modules.CollectionManagementService;
import org.xmldb.api.modules.XMLResource;

public class AddExample {
	public static void main(String args[]) throws Exception {
		String collection = "/prueba", file = "libros.xml";
		if (collection.startsWith("/db")) { // remove /db if specified
			collection = collection.substring(3);
		}
		// initialize driver
		String driver = "org.exist.xmldb.DatabaseImpl";
		Class<?> cl = Class.forName(driver);
		Database database = (Database) cl.newInstance();
		database.setProperty("create-database", "true");
		DatabaseManager.registerDatabase(database);
		// try to get collection
		Collection col = DatabaseManager.getCollection(
				"xmldb:exist://localhost:8082/exist/xmlrpc/db" + collection,
				"admin", "toor");
		if (col == null) {
			// collection does not exist: get root collection and create it
			Collection root = DatabaseManager.getCollection(
					"xmldb:exist://localhost:8082/exist/xmlrpc/db", "<<user>>",
					"<<pass>>");
			CollectionManagementService mgtService = (CollectionManagementService) root
					.getService("CollectionManagementService", "1.0");
			col = mgtService.createCollection(collection);
		}
		// create new XMLResource; an id will be assigned to the new resource
		XMLResource document = (XMLResource) col.createResource(null,
				"XMLResource");
		File f = new File(file);
		if (!f.canRead()) {
			System.err.println("can't read file " + file);
		}
		document.setContent(f);
		System.out.print("storing document " + document.getId() + "...");
		col.storeResource(document);
		System.out.println("ok.");
	}
}